<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from "vue";
import { centerMap, GETNOBASE } from "@/api";
import { registerMap, getMap } from "echarts/core";
import { optionHandle, regionCodes } from "./center.map";
import BorderBox13 from "@/components/datav/border-box-13";
import { ElMessage } from "element-plus";
import patientList from "@/mock/patientData";

import type { MapdataType } from "./center.map";

const option = ref({});
const code = ref("china");

withDefaults(
  defineProps<{
    title: number | string;
  }>(),
  {
    title: "患者分布地图",
  }
);

// 初始化所有省份数据为0
const initializeProvinceData = () => {
  const initializedData: { [key: string]: number } = {};
  
  // 遍历regionCodes，为每个省份设置默认值0
  Object.keys(regionCodes).forEach(provinceName => {
    // 排除中国整体
    if (provinceName !== '中国') {
      initializedData[provinceName] = 0;
    }
  });
  
  return initializedData;
};

// 处理患者数据，统计每个省份的患者数量
const processPatientData = () => {
  // 先初始化所有省份为0
  const provinceData = initializeProvinceData();
  
  patientList.forEach((patient: any) => {
    const address = patient.address;
    if (address) {
      let provinceName = "";
      
      // 从地址中提取省份名称
      if (address.includes("省")) {
        provinceName = address.split("省")[0] + "省";
      } else if (address.includes("自治区")) {
        if (address.includes("内蒙古")) {
          provinceName = "内蒙古自治区";
        } else if (address.includes("新疆")) {
          provinceName = "新疆维吾尔自治区";
        } else if (address.includes("西藏")) {
          provinceName = "西藏自治区";
        } else if (address.includes("广西")) {
          provinceName = "广西壮族自治区";
        } else if (address.includes("宁夏")) {
          provinceName = "宁夏回族自治区";
        } else {
          provinceName = address.split("自治区")[0] + "自治区";
        }
      } else if (address.includes("北京市") || address.includes("北京")) {
        provinceName = "北京市";
      } else if (address.includes("天津市") || address.includes("天津")) {
        provinceName = "天津市";
      } else if (address.includes("上海市") || address.includes("上海")) {
        provinceName = "上海市";
      } else if (address.includes("重庆市") || address.includes("重庆")) {
        provinceName = "重庆市";
      } else if (address.includes("香港")) {
        provinceName = "香港特别行政区";
      } else if (address.includes("澳门")) {
        provinceName = "澳门特别行政区";
      } else {
        // 尝试从regionCodes中匹配
        const matchedProvince = Object.keys(regionCodes).find(province => 
          address.includes(province.replace(/[省市自治区特别行政區]/g, ''))
        );
        provinceName = matchedProvince || address.substring(0, 3);
      }
      
      // 如果匹配到有效的省份名称，则增加计数
      if (provinceName && provinceData.hasOwnProperty(provinceName)) {
        provinceData[provinceName] += 1;
      }
    }
  });
  
  // 转换为地图需要的数据格式
  const mapDataList = Object.keys(provinceData).map(province => ({
    name: province,
    value: provinceData[province]
  }));
  
  console.log("完整的省份数据:", provinceData);
  return mapDataList;
};

const dataSetHandle = async (regionCode: string, list: any[]) => {
  const geojson: any = await getGeojson(regionCode);
  let cityCenter: any = {};
  let mapData: MapdataType[] = [];
  
  // 获取当前地图每块行政区中心点
  if (geojson.features) {
    geojson.features.forEach((element: any) => {
      cityCenter[element.properties.name] = element.properties.centroid || element.properties.center;
    });
  }
  
  // 处理数据，确保省份名称与地图匹配
  const processedList = list.map((item: any) => {
    return {
      name: item.name,
      value: item.value
    };
  });
  
  // 创建mapData（包含坐标信息）
  processedList.forEach((item: any) => {
    if (cityCenter[item.name]) {
      mapData.push({
        name: item.name,
        value: [...cityCenter[item.name], item.value] as [number, number, number]
      });
    }
  });
  
  await nextTick();
  option.value = optionHandle(regionCode, processedList, mapData);
};

const getData = async (regionCode: string) => {
  try {
    const patientDataList = processPatientData();
    console.log("患者分布数据", patientDataList);
    
    if (patientDataList.length > 0) {
      await dataSetHandle(regionCode, patientDataList);
    } else {
      ElMessage.warning("暂无患者数据");
      // 设置一个空的地图选项
      option.value = optionHandle(regionCode, [], []);
    }
  } catch (err) {
    ElMessage.error("数据处理失败");
    console.error(err);
  }
};

const getGeojson = (regionCode: string) => {
  return new Promise<any>(async (resolve) => {
    let mapjson = getMap(regionCode);
    if (mapjson) {
      mapjson = mapjson.geoJSON;
      resolve(mapjson);
    } else {
      try {
        mapjson = await GETNOBASE(`./map-geojson/${regionCode}.json`).then((data) => data);
        code.value = regionCode;
        registerMap(regionCode, {
          geoJSON: mapjson as any,
          specialAreas: {},
        });
        resolve(mapjson);
      } catch (error) {
        console.error("加载地图JSON失败:", error);
        resolve({ features: [] });
      }
    }
  });
};

onMounted(() => {
  getData(code.value);
});

const mapClick = (params: any) => {
  console.log("地图点击:", params);
  let xzqData = regionCodes[params.name];
  if (xzqData) {
    getData(xzqData.adcode);
  } else {
    window["$message"].warning("暂无下级地市");
  }
};
</script>

<template>
  <div class="centermap">
    <div class="maptitle">
      <div class="zuo"></div>
      <span class="titletext">{{ title }}</span>
      <div class="you"></div>
    </div>
    <div class="mapwrap">
      <BorderBox13>
        <div class="quanguo" @click="getData('china')" v-if="code !== 'china'">中国</div>
        <v-chart
          class="chart"
          :option="option"
          ref="centerMapRef"
          @click="mapClick"
          :autoresize="true"
          style="height: 100%; width: 100%;"
        />
      </BorderBox13>
    </div>
  </div>
</template>

<style scoped lang="scss">
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(92deg, #0072ff 0%, #00eaff 48.8525390625%, #01aaff 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("@/assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("@/assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 580px;
    width: 100%;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -46px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5), 0 0 6px rgba(0, 237, 237, 0.4);
      z-index: 10;
    }

    .chart {
      height: 100%;
      width: 100%;
    }
  }
}
</style>